﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Slaughter;
using Provenance.Infra.Repositories.Slaughter;
using Provenance.Write.Api.Application.Command.Slaughter;

namespace Provenance.Write.Api.Application.CommandHandler.Slaughter
{
    public class UpSlaughterEnterpriseCommandHandler : IRequestHandler<UpSlaughterEnterpriseCommand, ApiResult>
    {
        private readonly ISlaughterEnterpriseRepository _slaughterEnterpriseRepository;
        private readonly ILogger<UpSlaughterEnterpriseCommandHandler> _logger;
        private readonly IMapper _mapper;
        public UpSlaughterEnterpriseCommandHandler(ISlaughterEnterpriseRepository slaughterEnterpriseRepository, ILogger<UpSlaughterEnterpriseCommandHandler> logger, IMapper mapper)
        {
            _slaughterEnterpriseRepository = slaughterEnterpriseRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpSlaughterEnterpriseCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _slaughterEnterpriseRepository.GetAsync(x =>x.SlaughterEnterpriseId== request.SlaughterEnterpriseId);
                obj = _mapper.Map(request, obj);
                await _slaughterEnterpriseRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error updating slaughter enterprise: " + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
